package com.project.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.bean.UserInfoBean;
import com.project.result.GlobalHandleException;
import com.project.result.ResponseResult;
import com.project.result.ResultCode;
import com.project.service.IUserInfoService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Wangcm
 * @since 2021-03-10
 */
@RestController
@RequestMapping("/users")
public class UserInfoController {
    @Resource
    private IUserInfoService userInfoService;

    @PostMapping("/login")
    @ResponseResult
    public Object login(String userName,String userPwd) throws GlobalHandleException {
        // 把用户输入的账号和密码封装到shiro框架提供的token对象中
        UsernamePasswordToken token = new UsernamePasswordToken(userName, DigestUtils.sha256Hex(userPwd));
        Subject currentUser = SecurityUtils.getSubject();
        try{
            //主体提交登录请求到SecurityManager
            currentUser.login(token);
        }catch(IncorrectCredentialsException ice){
            throw new GlobalHandleException(ResultCode.USER_PASS_ERROR);
        }catch (UnknownAccountException uae){
            throw new GlobalHandleException(ResultCode.USER_NOT_EXIST);
        }catch (AuthenticationException ae){
            throw new GlobalHandleException(ResultCode.USER_AUTHENTICATION_ERROR);
        }catch (AuthorizationException ae){
            throw new GlobalHandleException(ResultCode.USER_AUTHORIZATION_ERROR);
        }
        return currentUser.getPrincipal();
    }

    @GetMapping("/checkLikes")
    public Object checkLikes(Integer comId){
        UserInfoBean userInfoBean = (UserInfoBean)SecurityUtils.getSubject().getPrincipal();
        if(userInfoService.checkLikes(userInfoBean.getUserId(), comId) == 0){
            return false;
        }
        return true;
    }


    @PostMapping("/addLikes")
    @ResponseResult
    public Object addLikes(int userId,int commentId){
        userInfoService.addLikes(userId, commentId);
        return null;
    }

    @PostMapping("/cancelLikes")
    @ResponseResult
    public Object cancelLikes(int userId,int commentId){
        userInfoService.cancelLikes(userId, commentId);
        return null;
    }

    @GetMapping
    @ResponseResult
    public Object loginUser(){
        return SecurityUtils.getSubject().getPrincipal();
    }



}

